home *** CD-ROM | disk | FTP | other *** search
- Path: pwolf-mac.qualcomm.com!user
- From: pwolf@qualcomm.com (Paul I. Wolf )
- Newsgroups: comp.lang.c
- Subject: Re: To malloc (new) or not to malloc? When is the question.
- Date: 9 Jan 1996 17:12:52 GMT
- Organization: Qualcomm, Inc.
- Message-ID: <pwolf-0901960912510001@pwolf-mac.qualcomm.com>
- References: <4ctvk3$ort@maverick.tad.eds.com>
- NNTP-Posting-Host: pwolf-mac.qualcomm.com
-
- In article <4ctvk3$ort@maverick.tad.eds.com>, fignet05.darrins@eds.com
- (Darrin Smith) wrote:
- [snip]
- > Why is it that you can do something like the following:
- > char *x;
- > x="Some really long string with no particular meaning";
- > and have no problems, but can't (safely) do something like this:
- > struct st1{char one[10];
- > char two[20];
- > char three[10];
- > };
- > st1 *sptr; //or struct st1 *sptr in C instead of C++
- > sptr=fread(....);
- >
- > This caused a program I was trying to debug to crash. When I allocated
- > memory for sptr (I used sptr=new st1; but I suppose malloc would have done
- > just as well) it worked fine.
- >
- > What is going on here? Why isn't memory set aside for st1 *sptr just as
- > it is for char *x? Before I did the new (or malloc) it seemed as though
- > my program was getting written over!
- >
- First example is incorrect. You may be thinking of declaring with initializing:
- char* x = "Some really long string with no particular meaning";
-
- Same thing works for second example if you initialize with constants:
- struct st1{char one[10];
- char two[20];
- char three[10];
- }* sptr= {0};
-
- The point is that memory allocatiion during initialization is required if
- you want the pointer to "automatically" point to memory which can be used.
- In your first example, the "x=" is NOT valid syntax for a sequence of
- characters. In your second example, memory for the structure was not
- allocated by your declaration of the pointer, so using the pointer for
- "fread()" puts information into unallocated memory.
-